<template>
  <d2-container>
    <div class="muse_filter_box">
      <el-form ref="filtersForm" :model="form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item>
              <el-select
                clearable
                style="width: 100%"
                v-model="form.id"
                filterable
                remote
                reserve-keyword
                placeholder="门店名称"
                :remote-method="fnStoreList"
                :loading="loading"
              >
                <el-option
                  v-for="item in storeList"
                  :key="item._id"
                  :label="item.name"
                  :value="item._id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-input placeholder="会员号" v-model="form.memberNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-input
                placeholder="手机号"
                v-model="form.cellphone"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-input
                placeholder="账单号"
                v-model="form.billNumber"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-date-picker
                type="datetime"
                style="width: 100%"
                value-format="yyyy-MM-dd HH:MM"
                v-model="form.startDate"
                placeholder="开始时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-date-picker
                type="datetime"
                style="width: 100%"
                v-model="form.endDate"
                value-format="yyyy-MM-dd HH:MM"
                placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-button type="primary" @click="filterSearch('filtersForm')"
              >搜索</el-button
            >
            <el-button @click="resetFormByFiltersForm('filtersForm')"
              >重置</el-button
            >
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="muse_table_box">
      <div class="muse_control_box">
        <el-button
          class="muse_float_left"
          type="primary"
          @click="$router.push({ name: 'changePoint' })"
          >新增消费记</el-button
        >
        <el-button
          class="muse_float_right"
          type="primary"
          @click="exportExpenseHistory()"
          >导出Excel</el-button
        >
        <!-- <el-button @click="deleteSelected">删除选中</el-button>
        <el-button @click="deleteAll">删除全部</el-button>-->
      </div>
      <div class="muse_control_box" style="text-align: left">
        <!-- <span class="sum_up_label">累计积分: {{totalPoint}}</span>
        <span class="sum_up_label">可用积分: {{currentPoint}}</span>
        <span class="sum_up_label">到期积分: {{expiredPoint}}</span> -->
        <span class="sum_up_label">使用积分: {{ usedPoint }}</span>
        <span class="sum_up_label">赠送积分: {{ storeGiftPoint }}</span>
        <span class="sum_up_label">待审积分: {{ storePendingPoint }}</span>

        <span class="sum_up_label" style="margin-left: 20px"
          >未审核订单数: {{ unverify || 0 }}</span
        >
        <span class="sum_up_label">未复核订单数: {{ unreviewed || 0 }}</span>
      </div>
      <el-table height="58vh" :data="tableData" style="width: 100%">
        <el-table-column prop="member.code" label="会员号" />
        <el-table-column prop="cellphone" label="手机号" />
        <el-table-column prop="createdAt" label="创建时间" width="150">
          <template slot-scope="{ row: { createdAt } }">{{
            createdAt | date("YYYY-MM-DD HH:mm")
          }}</template>
        </el-table-column>
        <el-table-column prop="reviewAt" label="复核时间" width="150">
          <template slot-scope="{ row: { reviewAt, review } }">
            <span v-if="review !== 0">
              {{ reviewAt | date("YYYY-MM-DD HH:mm") }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="verifyAt" label="审核时间" width="150">
          <template slot-scope="{ row: { verifyAt, verify } }">
            <span v-if="verify !== 0">{{
              verifyAt | date("YYYY-MM-DD HH:mm")
            }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="store.name" label="消费门店" />
        <el-table-column prop="billNumber" label="账单号" />
        <el-table-column prop="amount" label="消费金额" />
        <el-table-column prop="earnPoints" label="待审核积分">
          <template slot-scope="{ row: { verify, earnPoints } }">
            <span v-if="earnPoints > 0">
              {{ earnPoints }}({{
                verify === 0 ? "待审核" : verify === 1 ? "已通过" : "未通过"
              }})
            </span>
            <span v-else>
              {{ earnPoints }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="point" label="使用积分" />
        <el-table-column prop="member.point" label="积分余额" />
        <el-table-column prop="review" label="复核状态">
          <template slot-scope="{ row: { review } }">
            <span>
              {{ review === 0 ? "未复核" : review === 1 ? "通过" : "拒绝" }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="verify" label="积分审核状态">
          <template slot-scope="{ row: { verify, earnPoints } }">
            <span v-if="earnPoints > 0">
              {{ verify === 0 ? "待审核" : verify === 1 ? "已通过" : "未通过" }}
            </span>
            <span v-else> 无 </span>
          </template>
        </el-table-column>
        <el-table-column label="处理员工">
          <template slot-scope="{ row }">
            <div v-if="row.staff.length > 0">
              <p style="margin: 0">手机号:</p>
              {{ row.staff[0].cellphone }}
            </div>
            <div v-if="row.account.length > 0">
              <p style="margin: 0">PC账号:</p>
              {{ row.account[0].account }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="账单链接">
          <template slot-scope="{ row }">
            <span
              v-if="row.billImage && row.billImage.length > 0"
              style="color: blue; cursor: pointer"
              @click="
                () => {
                  previewImgs = row.billImage;
                  dialogVisible = true;
                }
              "
              >账单预览</span
            >
            <span
              v-else
              style="color: red; cursor: pointer"
              @click="
                () => {
                  dialogVisibleByUpload = true;
                  detailForm.id = row._id;
                }
              "
              >上传账单</span
            >
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button @click="deleteRow(scope.row)" type="text" size="small"
              >撤销</el-button
            >
            <el-button
              v-if="scope.row.review === 0"
              @click="reviewPassed(scope.row)"
              type="text"
              size="small"
              >复核通过</el-button
            >
            <el-button
              v-if="scope.row.review === 0"
              @click="reviewFailed(scope.row)"
              type="text"
              size="small"
              >复核拒绝</el-button
            >

            <el-button
              v-if="scope.row.verify === 0 && scope.row.earnPoints > 0"
              @click="fnPass(scope.row)"
              type="text"
              size="small"
              >审核通过</el-button
            >
            <el-button
              v-if="scope.row.verify === 0 && scope.row.earnPoints > 0"
              @click="fnRefuse(scope.row)"
              type="text"
              size="small"
              >审核拒绝</el-button
            >
            <el-button v-if="$store.getters.userInfo.roleName.indexOf('root') > -1" @click="changeMoney(scope.row)" type="text" size="small"
              >消费金额更新</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        class="muse_pagination"
        :background="true"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="paging.page"
        :page-sizes="paging.pageSizeAry"
        :page-size="paging.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paging.total"
      ></el-pagination>
    </div>

    <el-dialog
      title="账单上传"
      :visible.sync="dialogVisibleByUpload"
      width="50%"
      :before-close="handleClose"
    >
      <el-form ref="detailForm" :model="detailForm" label-width="100px">
        <el-form-item label="账单" prop="billImage">
          <banner v-model="detailForm.billImage"></banner>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('detailForm')"
            >确定</el-button
          >
          <el-button @click="resetForm('detailForm')">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      title="账单预览"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <viewer :images="previewImgs">
        <img
          style="width: 20%"
          v-for="src in previewImgs"
          :src="src"
          :key="src"
        />
      </viewer>
    </el-dialog>

    <el-dialog
      title="消费金额修改"
      :visible.sync="dialogVisibleByChangeMoney"
      width="30%"
    >
      <el-form
        ref="formByMoney"
        :model="formByMoney"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="消费金额" prop="newPrice">
          <el-input
            placeholder="消费金额"
            v-model="formByMoney.newPrice"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormByMoney('formByMoney')"
            >确定</el-button
          >
          <el-button @click="dialogVisibleByChangeMoney = false"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </d2-container>
</template>

<script>
import tableMixin from "../mixins/tableMixin";
import banner from "@/components/muse/banner/banner";
import {
  getExpenseHistoryList,
  recallUserExpenseHistory,
  exportExpenseHistory,
  verifyPassed,
  verifyFailed,
  reviewPassed,
  reviewFailed,
  getStoreList,
  uploadBillImage,
  changeExpenseHistoryPrice,
} from "@/api/admin";
import excel from "@/libs/util.excel.js";
export default {
  name: "expenseRecordList",
  mixins: [tableMixin],
  components: { banner },
  data() {
    return {
      form: {
        memberNo: "",
        cellphone: "",
        startDate: "",
        endDate: "",
      },
      detailForm: {
        id: "",
        billImage: [],
      },
      formByMoney: {
        id: "",
        newPrice: "",
      },
      rules: {
        newPrice: [
          {
            required: true,
            message: "请输入消费金额",
            trigger: "blur",
          },
        ],
      },
      storeList: [],
      expiredPoint: "",
      totalPoint: "",
      currentPoint: "",
      usedPoint: 0,
      storeGiftPoint: 0,
      storePendingPoint: 0,

      unverify: 0,
      unreviewed: 0,
      previewImgs: [],
      dialogVisible: false,
      dialogVisibleByUpload: false,
      dialogVisibleByChangeMoney: false,
    };
  },
  created() {
    this.getTableData();
    console.log(this.$store.getters.userInfo.roleName);
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.getTableData();
    });
  },
  methods: {
    // 获取列表数据
    async getTableData(value, type) {
      let params = {
        page:
          type === "page"
            ? value
              ? value
              : this.paging.page
            : this.paging.page,
        pageSize:
          type === "pageSize"
            ? value
              ? value
              : this.paging.pageSize
            : this.paging.pageSize,
      };
      params = Object.assign({}, params, this.form);
      const {
        code,
        data: {
          total,
          currentPage,
          data,
          pageSize,
          expiredPoint,
          totalPoint,
          currentPoint,
          usedPoint,
          storeGiftPoint,
          storePendingPoint,
          unverify,
          unreviewed,
        },
      } = await getExpenseHistoryList(params);
      this.paging.total = total;
      this.paging.pageSize = pageSize;
      this.paging.page = currentPage;
      this.tableData = data;

      this.expiredPoint = expiredPoint;
      this.totalPoint = totalPoint;
      this.currentPoint = currentPoint;
      this.usedPoint = usedPoint;
      this.storeGiftPoint = storeGiftPoint;
      this.storePendingPoint = storePendingPoint;

      this.unreviewed = unreviewed;
      this.unverify = unverify;
    },
    // 删除选中行
    deleteSelected() {
      this.wrapConfirm(1)
        .then(() => {
          console.log("delete selected row");
        })
        .catch(() => {});
    },
    // 删除全部
    deleteAll() {
      this.wrapConfirm(0)
        .then(() => {
          console.log("delete all");
        })
        .catch(() => {});
    },
    // 编辑该行
    editRow(row) {
      this.$router.push({
        name: "changeExpenseRecord",
        query: { id: row._id },
      });
      console.log("edit row", row);
    },
    // 删除该行
    deleteRow(row) {
      this.wrapConfirm(-1, "要撤销该条消费记录，是否继续？")
        .then(async () => {
          await recallUserExpenseHistory({ id: row._id });
          this.getTableData();
        })
        .catch(() => {});
    },
    exportExpenseHistory() {
      exportExpenseHistory(this.form).then((res) => {
        excel.exportRaw(res.data, "消费记录");
      });
    },
    fnPass(row) {
      this.wrapConfirm(-1, "确定要通过该审核积分？")
        .then(async () => {
          console.log(123);
          await verifyPassed({ id: row._id });
          this.getTableData();
        })
        .catch(() => {});
    },
    fnRefuse(row) {
      this.wrapConfirm(-1, "确定要拒绝该审核积分？")
        .then(async () => {
          await verifyFailed({ id: row._id });
          this.getTableData();
        })
        .catch(() => {});
    },
    reviewPassed(row) {
      this.wrapConfirm(-1, "确定要通过该复核积分？")
        .then(async () => {
          await reviewPassed({ id: row._id });
          this.getTableData();
        })
        .catch(() => {});
    },
    reviewFailed(row) {
      this.wrapConfirm(-1, "确定要拒绝该复核积分？")
        .then(async () => {
          await reviewFailed({ id: row._id });
          this.getTableData();
        })
        .catch(() => {});
    },
    async fnStoreList(e) {
      const params = {
        name: e,
      };
      this.loading = true;
      const {
        data: { data },
      } = await getStoreList(params);
      this.loading = false;
      this.storeList = data;
    },
    // 账单上传
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await uploadBillImage(this.detailForm);
          this.dialogVisibleByUpload = false;
          this.getTableData();
        } else {
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs["detailForm"].resetFields();
      this.detailForm.id = "";
      this.detailForm.billImage = [];
      this.dialogVisibleByUpload = false;
    },

    resetFormByFiltersForm(formName) {
      this.$refs[formName].resetFields();
      this.form = {};
      this.getTableData();
    },
    changeMoney(row) {
      this.dialogVisibleByChangeMoney = true;
      this.formByMoney = {
        id: row._id,
        newPrice: "",
      };
    },
    submitFormByMoney(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          await changeExpenseHistoryPrice(this.formByMoney);
          this.dialogVisibleByChangeMoney = false;
          this.getTableData();
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped>
.sum_up_label {
  font-size: 16px;
  margin-right: 20px;
  font-weight: bold;
}
</style>

<style>
.viewer-backdrop {
  z-index: 9999 !important;
}
</style>